package com.cindata

import com.cindata.dictionary.*

class Estate
{

    // EstateImportBatch batch

    String externalId
    // 外部ID
    Province province
    // 省
    City city
    // 城市
    District district
    // 行政区

    EstateStatusDict estateStatus
    //押品状态1： 在押  2： 解押  3： 处置  2： 清退
    Boolean isEstate = true
    // 是否押品

    MortgageStatusDict mortgageStatus
    MortgageType mortgageType

    Long streetId
    String streetName
    Long communityId
    String communityName
    String communityAddress
    Long buildingId
    String buildingName
    Long unitId
    String unitName
    Long houseId
    String houseName
    Integer totalBuildingNum
    Integer totalHouseNum

    Integer buildYear
    BigDecimal buildArea
    BuildingTypeDict buildingType
    // 建筑类型

    /*评估单价*/
    BigDecimal unitPrice
    /*评估总价*/
    BigDecimal totalPrice

    BigDecimal ltv
    // 抵押率 （%）
    BigDecimal cltv
    //动态抵押率 （%）

    /*押品信息*/
    String sourceAddress
    BigDecimal sourceBuildArea
    Integer sourceTotalFloor
    Integer sourceCurrentFloor

    BigDecimal loansEvaluateTotalPrice
    // 贷款评估总价
    BigDecimal loansEvaluatePrice
    //贷款评估单价
    BigDecimal loansAmount
    // 贷款金额
    BigDecimal loansBalance
    //贷款余额

    Date startDate
    Date endDate

    Date matchDate
    // 匹配时间
    Date valuationDate
    //评估时间

    Double x
    // 经度
    Double y
    // 纬度
    Integer loansDuration
    //    最初应还款期数（月）
    Integer remainTime
    //    当前剩余还款期数（月）
    Account account
    // 直属管理机构(银行网点)
    Account developer
    // 所属开发商

    Date createdDate = new Date()
    Date modifiedDate = new Date()
    User createBy
    User modifyBy

    // 价值波动率
    BigDecimal priceFluctuationsRatio
    // 风险预警处理类型
    RiskWarningDealTypeDict dealType
    // 预警状态
    RiskWarningStatusDict warningStatus


    // 全量押品分析统计
    // BusinessType businessType         // 业务小类
    String accountName
    // 抵押权人
    LoanRightsTypeDict loanRightsType
    // 权利种类
    LoanPropertiesDict loanProperties
    // 贷款性质
    Double soldPrice = 0
    // 房地售价
    Double actuallyUseArea = 0
    // 套内面积
    Double sharedUseArea = 0
    // 分摊面积
    HouseNatureDict houseNature
    // 房屋性质
    HouseTypeDict estateType
    // 房屋类型

    // 不良资产评估
    Boolean isNonPerformingAsset = false
    // 是否不良
    String contactFullName
    // 联系人
    String contactCellphone
    // 联系电话
    Double loadArea = 0
    // 土地面积
    Double auctionPrice = 0
    // 拍卖价格

    Mortgage mortgage

    // 新增字段
    String name
    // 质押物名称
    String ownershipNumber
    // 房屋所有权证书号码（所有权编号）
    String fullName
    // 抵押人名称
    ContactIdentityType identityType
    // 抵押人证件类型
    String idNumber
    // 抵押人证件号码
    String loanCardNumber
    // 抵押人贷款卡编号
    String commonOwnerFullName
    // 其他共同所有人
    Double sharePoint
    // 所占份额
    Boolean isApplayPurchaseAsset = false
    // 此抵押物是否当前申请所购资产
    String rightOfMortgage
    // 抵押权顺位
    BigDecimal firstGuaranteedAmount
    // 在先担保金额

    String usage
    // 使用情况 1出租 2自用 3闲置 4其他
    String lessee
    // 承租人
    Date leaseStartDate
    // 租赁起始日期
    Date leaseEndDate
    // 租赁到期日期
    BigDecimal annualRents
    // 年租金（万元）
    BigDecimal purchaseTotalPrice
    // 购买总价
    BigDecimal purchaseUnitPrice
    // 购买单价
    BigDecimal firstPayment
    // 首付款
    CurrencyDict currency
    // 币种
    Integer age
    // 房龄
    Boolean landUsageCertificate = false
    // 有无土地使用权证书
    String landUsageCertificateNo
    // 土地使用权证书号码（土地使用权证编号）
    Boolean mortgageRegistration = false
    // 是否已办理抵押登记
    String mortgageRegistrationOrg
    // 抵押登记机构
    String hisWarrantNumber
    // 他项权利证书号码
    String sealUpSituation
    // 查封情况 1.未查封 2.已查封
    String sealUpRights
    // 查封顺位 1.我行一手查封 2.我行二手查封 3.我行三手及以上查封
    String sealUpAccount
    // 查封法院
    Date sealUpDate
    // 查封时间
    String forwardHand
    // 前手查封人
    String situationOfCurrentSeal
    // 当前查封物执行情况 1.申请执行 2.执行立案 3.评估 4.一拍 5.二拍  6.三拍 7.变卖 8.以物抵债、9处置完毕
    BigDecimal disposalAmount
    // 处置金额

    Cashability cashability
    // 变现能力 1.通用且变现容易，2.通用但变现较不易，专用性强
    String valueVolatility
    // 价值波动性 1.价值波动大；2.价值波动中；3.有升值潜力或波动小
    String seizureOfConvenience
    // 查封便利性 1.无查封障碍的不动产，动产由我行监管；2.查封有一定障碍的不动产，动产存放地点相对固定但非我行监管；3.查封有障碍的不动产，动产存放地点难掌握和控制
    String relationOfMortgagor
    // 抵质押物与借款人相关性 1.本人 2.第三方
    String legalValidity
    // 法律有效性 1.担保合法且手续完整 2.担保不合法或手续基本无效
    Double firstEvaluatePrice
    // 初次评估价值
    Account firstEvaluateAccount
    // 初次评估机构
    Double latestEvaluatePrice
    // 最新评估价值
    Account latestEvaluateAccount
    // 最新评估机构
    Date latestEvaluateDate
    // 最新评估日期
    Date nextEvaluateDate
    // 下次评估日期
    Double actualMortgageRate
    // 实际抵质押率 (实际抵质押率=债权本息总额÷抵押物评估价值（或质押物认定价值）×100%)
    Double mortgageRateUpperLimit
    // 抵质押率上限
    String description
    // 抵质押物说明
    String registerFullName
    // 登记人
    String registerAccount
    // 登记机构
    Date registerDate
    // 登记日期
    Date registerUpdateDate
    // 更新日期

    BigDecimal loansbalance

    // static hasMany = [valuationHistory: ValuationHistory]
    BigDecimal rentUnitPrice
    //出租单价
    Double rentArea
    //出租面积

//    Workflow workflow


    static mapping = {
        autowire true
    }

    static constraints = {

        // batch nullable: true, blank: true
        loansbalance nullable: true, blank: true
        
        mortgage nullable: true, blank: true
        mortgageStatus nullable: true, blank: true
        mortgageType nullable: true, blank: true

        province nullable: true, blank: true, comment: '省'
        city nullable: true, blank: true, comment: '城市'
        district nullable: true, blank: true, comment: '行政区'
        streetName maxSize: 128, nullable: true, blank: true, comment: '街道'
        streetId nullable: true, blank: true, comment: '街道'
        estateStatus nullable: true, blank: true, comment: '押品状态'
        isEstate nullable: true, blank: true, comment: '是否押品'

        communityName maxSize: 128, nullable: true, blank: true
        communityAddress maxSize: 128, nullable: true, blank: true, comment: '小区地址'
        buildingName maxSize: 128, nullable: true, blank: true
        unitName maxSize: 128, nullable: true, blank: true
        houseName maxSize: 128, nullable: true, blank: true

        communityId nullable: true, blank: true
        buildingId nullable: true, blank: true
        unitId nullable: true, blank: true
        houseId nullable: true, blank: true

        externalId maxSize: 128, nullable: true, blank: true
        externalId unique: true

        buildYear maxSize: 4, nullable: true, blank: true
        buildArea precision: 7, scale: 2, nullable: true, blank: true
        buildingType nullable: true, blank: true, comment: '建筑类型'

        unitPrice precision: 15, scale: 2, nullable: true, blank: true
        totalPrice precision: 15, scale: 2, nullable: true, blank: true

        ltv precision: 5, scale: 4, nullable: true, blank: true
        cltv precision: 5, scale: 4, nullable: true, blank: true

        sourceAddress maxSize: 255, nullable: true, blank: true
        sourceBuildArea precision: 7, scale: 2, nullable: true, blank: true
        sourceTotalFloor maxSize: 10, nullable: true, blank: true
        sourceCurrentFloor maxSize: 10, nullable: true, blank: true

        loansEvaluateTotalPrice precision: 15, scale: 2, nullable: true, blank: true
        loansEvaluatePrice precision: 15, scale: 2, nullable: true, blank: true
        loansAmount precision: 15, scale: 2, nullable: true, blank: true
        loansDuration maxSize: 10, nullable: true, blank: true
        loansBalance precision: 15, scale: 2, nullable: true, blank: true

        startDate nullable: true, blank: true
        endDate nullable: true, blank: true

        createdDate nullable: true, blank: true
        modifiedDate nullable: true, blank: true
        createBy nullable: true, blank: true
        modifyBy nullable: true, blank: true
        remainTime nullable: true, blank: true
        matchDate nullable: true, blank: true
        valuationDate nullable: true, blank: true

        x nullable: true, blank: true
        y nullable: true, blank: true

        account nullable: true, blank: true, comment: '直属管理机构'
        developer nullable: true, blank: true, comment: '所属开发商'

        priceFluctuationsRatio  precision: 8, scale: 4,nullable: true, blank: true
        dealType nullable: true, blank: true
        warningStatus nullable: true, blank: true

        // businessType nullable: true, blank: true
        accountName maxSize: 64, nullable: true, blank: true
        loanRightsType nullable: true, blank: true
        loanProperties nullable: true, blank: true
        soldPrice nullable: true, blank: true
        actuallyUseArea nullable: true, blank: true
        sharedUseArea nullable: true, blank: true
        houseNature nullable: true, blank: true
        estateType nullable: true, blank: true

        // 不良资产评估
        isNonPerformingAsset nullable: true, blank: true
        contactFullName maxSize: 64, nullable: true, blank: true
        contactCellphone maxSize: 11, nullable: true, blank: true
        loadArea nullable: true, blank: true
        auctionPrice nullable: true, blank: true

        totalBuildingNum nullable: true, blank: true, comment: '总楼栋数'
        totalHouseNum nullable: true, blank: true, comment: '总户数'


        name maxSize: 64, nullable: true, blank: true, comment: '质押物名称'
        ownershipNumber maxSize: 64, nullable: true, blank: true, comment: '房屋所有权证书号码（所有权编号）'
        fullName maxSize: 20, nullable: true, blank: true, comment: '抵押人名称'
        identityType nullable: true, blank: true, comment: '抵押人证件类型'
        idNumber maxSize: 18, nullable: true, blank: true, comment: '抵押人证件号码'
        loanCardNumber maxSize: 50, nullable: true, blank: true, comment: '抵押人贷款卡编号'
        commonOwnerFullName maxSize: 20, nullable: true, blank: true, comment: '其他共同所有人'
        sharePoint nullable: true, blank: true, comment: '所占份额'
        isApplayPurchaseAsset nullable: true, blank: true, comment: '此抵押物是否当前申请所购资产'
        rightOfMortgage maxSize: 64, nullable: true, blank: true, comment: '抵押权顺位'
        firstGuaranteedAmount nullable: true, blank: true, comment: '在先担保金额'

        usage maxSize: 64, nullable: true, blank: true, comment: '使用情况'
        lessee maxSize: 64, nullable: true, blank: true, comment: '承租人'
        leaseStartDate nullable: true, blank: true, comment: '租赁起始日期'
        leaseEndDate nullable: true, blank: true, comment: '租赁到期日期'
        annualRents nullable: true, blank: true, comment: '年租金'
        purchaseTotalPrice nullable: true, blank: true, comment: '购买总价'
        purchaseUnitPrice nullable: true, blank: true, comment: '购买单价'
        firstPayment nullable: true, blank: true, comment: '首付款'
        currency nullable: true, blank: true, comment: '币种'
        age nullable: true, blank: true, comment: '房龄'
        landUsageCertificate nullable: true, blank: true, comment: '有无土地使用权证书'
        landUsageCertificateNo maxSize: 64, nullable: true, blank: true, comment: '土地使用权证书号码'
        mortgageRegistration maxSize: 64, nullable: true, blank: true, comment: '是否已办理抵押登记'
        mortgageRegistrationOrg maxSize: 64, nullable: true, blank: true, comment: '抵押登记机构'
        hisWarrantNumber maxSize: 64, nullable: true, blank: true, comment: '他项权利证书号码'
        sealUpSituation maxSize: 64, nullable: true, blank: true, comment: '查封情况'
        sealUpRights maxSize: 64, nullable: true, blank: true, comment: '查封顺位'
        sealUpAccount maxSize: 64, nullable: true, blank: true, comment: '查封法院'
        sealUpDate nullable: true, blank: true, comment: '查封时间'
        forwardHand maxSize: 20, nullable: true, blank: true, comment: '前手查封人'
        situationOfCurrentSeal maxSize: 64, nullable: true, blank: true, comment: '当前查封物执行情况'
        disposalAmount nullable: true, blank: true, comment: '处置金额'

        cashability nullable: true, blank: true, comment: '变现能力'
        valueVolatility maxSize: 50, nullable: true, blank: true, comment: '价值波动性'
        seizureOfConvenience maxSize: 50, nullable: true, blank: true, comment: '查封便利性'
        relationOfMortgagor maxSize: 50, nullable: true, blank: true, comment: '抵质押物与借款人相关性'
        legalValidity maxSize: 50, nullable: true, blank: true, comment: '法律有效性'
        firstEvaluatePrice nullable: true, blank: true, comment: '初次评估价值'
        firstEvaluateAccount nullable: true, blank: true, comment: '初次评估机构'
        latestEvaluatePrice nullable: true, blank: true, comment: '最新评估价值'
        latestEvaluateAccount nullable: true, blank: true, comment: '最新评估机构'
        latestEvaluateDate nullable: true, blank: true, comment: '最新评估日期'
        nextEvaluateDate nullable: true, blank: true, comment: '下次评估日期'
        actualMortgageRate nullable: true, blank: true, comment: '实际抵质押率'
        mortgageRateUpperLimit nullable: true, blank: true, comment: '抵质押率上限'
        description maxSize: 200, nullable: true, blank: true, comment: '抵质押物说明'
        registerFullName nullable: true, blank: true, comment: '登记人'
        registerAccount maxSize: 50, nullable: true, blank: true, comment: '登记机构'
        registerDate nullable: true, blank: true, comment: '登记日期'
        registerUpdateDate nullable: true, blank: true, comment: '更新日期'

        rentUnitPrice precision: 15, scale: 2, nullable: true, blank: true, comment: '出租单价'
        rentArea precision: 7, scale: 2,nullable: true, blank: true,comment: '出租面积'
//        workflow nullable: true, blank: true, comment: '押品登记流程'


    }

    def springSecurityService

    def beforeInsert()
    {
        registerAccount = account
        registerDate = new Date()
    }

    def synCollateralAndMortgage(Estate estate)
    {
        def mortgageTemp = null
        if (EstateImport.findByExternalId(estate.externalId))
        {
            // 同步创建房贷数据，只此一次
            mortgageTemp = Mortgage.CreateFromEstate(estate)
        }
        
        // 存储 collateral 和 MortgageCollateral
        def collateral = new Collateral()
        collateral.province = estate.province
        collateral.city = estate.city
        collateral.district = estate.district
        collateral.estateStatus = estate.estateStatus
        collateral.isEstate = estate.isEstate
        collateral.unitPrice = estate.unitPrice
        collateral.totalPrice = estate.totalPrice
        collateral.valuationDate = estate.valuationDate
        collateral.ltv = estate.ltv
        collateral.cltv = estate.cltv
        collateral.account = estate.account
        collateral.externalId = estate.externalId
        collateral.name = estate.name
        collateral.fullName = estate.fullName
        collateral.identityType = estate.identityType
        collateral.idNumber = estate.idNumber
        collateral.loanCardNumber = estate.loanCardNumber
        collateral.commonOwnerFullName = estate.commonOwnerFullName
        collateral.sharePoint = estate.sharePoint
        collateral.cashability = estate.cashability
        collateral.valueVolatility = estate.valueVolatility
        collateral.seizureOfConvenience = estate.seizureOfConvenience
        collateral.relationOfMortgagor = estate.relationOfMortgagor
        collateral.legalValidity = estate.legalValidity
        collateral.firstEvaluatePrice = estate.firstEvaluatePrice
        collateral.firstEvaluateAccount = estate.firstEvaluateAccount
        collateral.latestEvaluatePrice = estate.latestEvaluatePrice
        collateral.latestEvaluateAccount = estate.latestEvaluateAccount
        collateral.latestEvaluateDate = estate.latestEvaluateDate
        collateral.nextEvaluateDate = estate.nextEvaluateDate
        collateral.actualMortgageRate = estate.actualMortgageRate
        collateral.mortgageRateUpperLimit = estate.mortgageRateUpperLimit
        collateral.description = estate.description
        collateral.registerFullName = estate.registerFullName
        collateral.registerAccount = estate.registerAccount
        collateral.registerDate = estate.registerDate
        collateral.registerUpdateDate = estate.registerUpdateDate
        collateral.createBy = estate.createBy
        collateral.estate = estate
        collateral.modifiedDate = new Date()
        collateral.type = CollateralType.findByCode("estate")
        collateral.sourceClass = "estate"
        if (EstateImport.findByExternalId(this.externalId))
        {
            collateral.status = "Completed"
        }
        else
        {
            collateral.status = "Pending"
        }

        if (collateral.validate())
        {
            collateral.save(flush:true)
        }
        else
        {
            println collateral.errors
        }

        if (EstateImport.findByExternalId(this.externalId)) 
        {
            def mortgageCollateral = new MortgageCollateral()
            mortgageCollateral.collateral = collateral
            mortgageCollateral.mortgage = mortgageTemp
            if (mortgageCollateral.validate()) 
            {
                mortgageCollateral.save()
            }
            else
            {
                println mortgageCollateral.errors
            }
        }
    }

    def beforeUpdate()
    {
        modifiedDate = new Date()
        def username = springSecurityService?.getPrincipal()?.username
        modifyBy = User.findByUsername(username)
        registerUpdateDate = new Date()
        if (firstEvaluatePrice && latestEvaluatePrice) 
        {
            priceFluctuationsRatio = (latestEvaluatePrice - firstEvaluatePrice) / firstEvaluatePrice
        }
        
        def collateral = Collateral.findByEstate(this)
        if (collateral) 
        {
            collateral.latestEvaluatePrice = latestEvaluatePrice
            collateral.latestEvaluateDate = latestEvaluateDate
            collateral.save()
        }
    }

    def getBaidu()
    {
        if (x && y)
        {
            def point = Trans.Gcj02ToBd(x, y)?.split(",")
            point ? [x: point[0], y: point[1]] : []
        }
    }

    // 获得应当还款的期数
    def getShouldRepaymentDate()
    {
        //        DateTime dt = new DateTime(endDate)
        //        dt.monthOfYear()
        Calendar cEndDate = Calendar.getInstance()
        cEndDate.setTime(endDate)
        cEndDate.add(Calendar.MONTH, remainTime)
        cEndDate.getActualMaximum(Calendar.DAY_OF_MONTH)
        return cEndDate.getTime()
    }

    // 公共过滤Org方法
    static FilterAccount(String sql, HashMap params, User currentUser)
    {

        def accountList = currentUser.getCurUserManageAccount()
        if (accountList)
        {
            sql += " and e.account in (:accountList) "
            params['accountList'] = accountList
        }
        return sql
    }
}
